<template>
  <div>
<el-card style="">
    <el-card class="box">
      <el-row>
        <el-col :span="12">
          <span class="font"></span>
        </el-col>
        <el-col :span="8">
          <el-tooltip class="item" effect="light" content="删除习题夹" placement="top-start">
            <el-button  icon="el-icon-minus" size="mini" @click="folderEditButton=!folderEditButton">
            </el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="5">
          <el-tooltip class="item" effect="light" content="新建习题夹" placement="top-start">
            <el-button  icon="el-icon-plus" size="mini" @click="openfolder">
            </el-button>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-divider></el-divider>
          <el-tree
            :data="tree"
            ref="tre"
            highlight-current
            node-key="id"
            @node-click="handleNodeClick()"
          >
             <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span >
          <el-button
            v-if="folderEditButton"
            type="text"
            size="mini"
            @click="() => deletefolder(node, data)">
            Delete
          </el-button>
        </span>
      </span>
      </el-tree>
    </el-card>
  <el-card style="float:right;width:83%">
    <h2>{{currentlabel}}</h2>
    <el-row>
        <el-tooltip v-if="editsort==false" class="item" effect="light" content="设置排序 删除" placement="top-start">
          <el-button size="small" @click="iseditsort()" icon="el-icon-edit" ></el-button>
        </el-tooltip>
      <template v-else-if="editsort==true">
        <el-popconfirm
          confirmButtonText='保存'
          cancelButtonText='取消'
          icon="el-icon-info"
          iconColor="green"
          title="确定要保存排序吗？"
          @onConfirm="updatesort()"
          @onCancel="editsort=false"
        >
          <el-button  size="small" type="success" slot="reference">保存</el-button>
        </el-popconfirm>
      </template>
<!--         <el-button  v-if="editsort" @click="restartSort" icon="el-icon-refresh-right" ></el-button>-->
        <el-tooltip class="item" effect="light" content="添加习题到习题夹" placement="top-start">
          <el-button  size="small" type="warning" :disabled="currentlabel==''" icon="el-icon-plus"  @click="openquestionadd"></el-button>
        </el-tooltip>
      <el-button size="small" type="primary" @click="dialogpaper=true">生成试卷</el-button>
    </el-row>

     <template >
      <el-table
        ref="folderdata"
        :data="folderdata"
        max-height="600"
        border
        :default-sort = "{prop: 'sort', order: 'Ascending'}"
      >
        <el-table-column
          label="大题序号"
          sortable
          prop="sort"
          width="90">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="13">
                <el-row>
                  <el-button  v-if="editsort" @click="up(scope.$index,scope.row)" icon="el-icon-top" size="mini" circle ></el-button>
                </el-row>
                <el-row>
                  <el-col :span="19">
                    <el-button  @click="down(scope.$index,scope.row)" v-if="editsort" icon="el-icon-bottom" size="mini" circle></el-button>
                  </el-col>
                  <el-col :span="4">
                    <template v-if="editsort">
                      <el-popconfirm
                        confirmButtonText='删除'
                        cancelButtonText='取消'
                        icon="el-icon-info"
                        iconColor="green"
                        title="确定要删除习题吗？"
                        @onConfirm="deletefolderAndQuestion(scope.row.id)"
                        v-if="editsort"
                      >
                        <el-button slot="reference"  type="danger" icon="el-icon-delete" size="mini"circle></el-button>
                      </el-popconfirm>
                    </template>

                  </el-col>
                  </el-row>
              </el-col>
                <el-col :span="8">
                  <el-row>
                    {{scope.row.sort}}
                  </el-row>
                </el-col>
            </el-row>
          </template>
        </el-table-column>
          <el-table-column
         label="大题"
          prop="content"
         
          width="100">
        </el-table-column>
        <el-table-column
         label="大题类型"
          prop="content"
         
          width="100">
        </el-table-column>
        <el-table-column
         label="每题分值"
          prop="每题分值"
          width="100"
         >
        </el-table-column>
        <el-table-column
          label="建议总时长"
          prop="useCount"
          width="120">
        </el-table-column>
        <el-table-column
          label="难度"
          prop="difficulty"
          width="200">
          <template slot-scope="{row}" >
            <el-rate v-model="row.difficulty"
                     :colors="['#99A9BF', '#E37969', '#F40808']"
                     disabled
                     show-text
                     :texts="diff"
                     text-color="#ff9900" ></el-rate>
          </template>
        </el-table-column>
      </el-table>
    </template>


    <template >

      <el-table
        ref="folderdata"
        :data="folderdata"
        max-height="600"
        border
        :default-sort = "{prop: 'sort', order: 'Ascending'}"
      >
        <el-table-column
          label="题号"
          sortable
          prop="sort"
          width="90">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="13">
                <el-row>
                  <el-button  v-if="editsort" @click="up(scope.$index,scope.row)" icon="el-icon-top" size="mini"circle ></el-button>
                </el-row>
                <el-row>
                  <el-col :span="19">
                    <el-button  @click="down(scope.$index,scope.row)" v-if="editsort" icon="el-icon-bottom"size="mini"circle></el-button>
                  </el-col>
                  <el-col :span="4">
                    <template v-if="editsort">
                      <el-popconfirm
                        confirmButtonText='删除'
                        cancelButtonText='取消'
                        icon="el-icon-info"
                        iconColor="green"
                        title="确定要删除习题吗？"
                        @onConfirm="deletefolderAndQuestion(scope.row.id)"
                        v-if="editsort"
                      >
                        <el-button slot="reference"  type="danger" icon="el-icon-delete" size="mini"circle></el-button>
                      </el-popconfirm>
                    </template>

                  </el-col>
                  </el-row>
              </el-col>
                <el-col :span="8">
                  <el-row>
                    {{scope.row.sort}}
                  </el-row>
                </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="题干"
          width="600">
        </el-table-column>
        <el-table-column
          prop="answer"
          width="100"
          label="答案">
        </el-table-column>
        <el-table-column
          label="引用次数"
          prop="useCount"
          width="80">
        </el-table-column>
        <el-table-column
          label="难度"
          prop="difficulty"
          width="200">
          <template slot-scope="{row}" >
            <el-rate v-model="row.difficulty"
                     :colors="['#99A9BF', '#E37969', '#F40808']"
                     disabled
                     show-text
                     :texts="diff"
                     text-color="#ff9900" ></el-rate>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <el-pagination
      :current-page="folderpage"
      :page-size="folderlimit"
      :total="foldertotal"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchDatafolder"
    />
  </el-card>
</el-card>
    <el-dialog
      title="新建文件夹"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="40%"
      :before-close="handleClose">
        <el-form ref="form" :model="folder" >
          <el-form-item label="文件夹名">
            <el-input v-model="folder.label"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addfolder">确 定</el-button>
     </span>
    </el-dialog>

    <el-drawer
      title="习题添加"
      :visible.sync="addquestiondialog"
      :before-close="handleClose"
      direction="ltr"
      size="50%">
      <div>
        <section class="c-s-dl">
          <dl>
            <dt>
              <span class="c-999 fsize14">课程类别</span>
            </dt>
            <dd class="c-s-dl-li">
              <ul class="clearfix">

                <li v-for="(item,index) in subjectNestedList" :key="index" :class="{active:oneIndex==index}">
                  <a :title="item.title" href="#" @click="searchOne(item.id,index)">{{item.title}}</a>
                </li>
              </ul>
            </dd>
          </dl>
          <dl>
            <dt>
              <span class="c-999 fsize14"></span>
            </dt>
            <dd class="c-s-dl-li">
              <ul class="clearfix">
                <li v-for="(item,index) in subSubjectList" :key="index" :class="{active:twoIndex==index}">
                  <a :title="item.title" href="#" @click="searchTwo(item.id,index)">{{item.title}}</a>
                </li>
              </ul>
            </dd>
          </dl>
          <div class="clear"></div>
        </section>
        <template>
          <el-table
            border
            :data="coursedata"
            style="width: 95%"
            max-height="500">
            <el-table-column
              fixed
              prop="title"
              label="课程标题"
              width="200">
            </el-table-column>
            <el-table-column
              prop="lessonNum"
              label="课程数"
              width="60">
            </el-table-column>
            <el-table-column
              prop="viewCount"
              label="浏览数量"
              width="60">
            </el-table-column>
            <el-table-column
              prop="teacherId"
              label="教师"
              width="120">
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              width="120">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="getcourseInfo(scope.row.id)">
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page="page"
            :page-size="limit"
            :total="total"
            style="padding: 30px 0; text-align: center;"
            layout="total, prev, pager, next, jumper"
            @current-change=""
          />
        </template>
        <el-drawer
          :title="'添加习题至 '+this.currentlabel+'习题夹'"
          :append-to-body="true"
          size="80%"
          :visible.sync="innerDrawer">
          <template>
            <el-table
              ref="multipleTable"
              @selection-change="handleSelectionChange"
              :data="tableData"
              tooltip-effect="dark"
              style="width: 98%"
              border
              max-height="500"
              >
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="id">
                      <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item label="时长">
                      <span>{{ props.row.time}}</span>
                    </el-form-item>
                    <el-form-item label="类型">
                      <span>{{ props.row.type }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ props.row.gmtCreate}}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column
                label="题干"
                prop="content"
                width="500"
              >
              </el-table-column>
              <el-table-column
                label="答案"
                prop="answer"
                width="400"
              >
              </el-table-column>
              <el-table-column
                label="引用次数"
                prop="useCount"
              width="60">
              </el-table-column>
              <el-table-column
                label="难度"
                prop="difficulty"
                width="200">
                <template slot-scope="{row}" >
                  <el-rate v-model="row.difficulty"
                           :colors="['#99A9BF', '#E37969', '#F40808']"
                           disabled
                           show-text
                           :texts="diff"
                           text-color="#ff9900" ></el-rate>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                prop="title"
                >
              </el-table-column>
            </el-table>
          </template>
          <!-- 分页 -->
          <el-pagination
            :current-page="page"
            :page-size="limit"
            :total="total"
            style="padding: 30px 0; text-align: center;"
            layout="total, prev, pager, next, jumper"
            @current-change=""
          />

          <el-row >
            <el-col :span="6" style="position: relative;left: 30px;" >
              <el-button @click="innerDrawer=false">取 消</el-button>
              <el-button type="primary" @click="addquestion">添 加</el-button>
            </el-col>
          </el-row>
        </el-drawer>
<el-row >
  <el-col ><el-button style="position: relative;left: 600px;"@click="addquestiondialog = false">取 消</el-button></el-col>
</el-row>
      </div>

    </el-drawer>

    <el-dialog
      title="生成试卷"
      :visible.sync="dialogpaper"
      v-if="dialogpaper"
      width="40%"
      :before-close="handleClose">
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogpaper = false">取 消</el-button>
    <el-button type="primary" @click="handleDownLoad">下载</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import course from "api/course";
import questionAndFolser from "api/questionAndFolder"
import homework from "api/homework";
import question from "api/question";
import file from "api/file";
import student from "api/student";
export default {
name: "selfquestion",
  data() {
    return {
      total: 0, // 总记录数
      page: 1, // 页码
      limit: 10, // 每页记录数

      foldertotal: 0, // 总记录数
      folderpage: 1, // 页码
      folderlimit: 10, // 每页记录数
      diff:["无聊","容易","中等","费时","极难"],
      folderdata:[],
      coursedata:[],
      searchObj: {}, // 查询表单对象
      oneIndex:-1,
      twoIndex:-1,
      subSubjectList:[],
      subjectNestedList:[],
      percentage: 0,
      editsort:false,
      innerDrawer:false,
      addquestiondialog:false,
      dialogVisible: false,
      folderEditButton:false,
      dialogpaper:false,
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      maxid:0,
      tableData: [],
      currentfolderId:'',
      currentlabel:'',
      folder:{
        label:'',
        teacherId:'',
        parentId:0,
        sort:0,
      },
      multipleSelection: [{id:'',sort:0}],
      questionupdate:[],
      isDeletefolderquestion:false

    }
  },
  created() {
    this.loginInfo = this.$store.state.userinfo
   this.initfolderList()
  },

  methods: {
    fetchDatafolder(page = 1) { // 调用api层获取数据库中的数据
      this.folderpage = page
      this.listLoading = true
      this.searchObj.classs=this.id
      this.searchObj.classs=this.classId
      student.getPageList(this.page, this.limit, this.searchObj).then(response => {

        // debugger 设置断点调试

        this.list = response.data.data.rows

        this.total = response.data.data.total

        this.listLoading = false
      }).catch(error=>{

      })
    },
    handleDownLoad(){
      file.downPdf(this.loginInfo.number,this.currentfolderId,this.currentlabel)
      .then((res) => {
                if (res) {
                  let blob = new Blob([res.data], {
                    type: "application/octet-stream;charset=utf-8",
                  }); // res就是接口返回的文件流了
                  let objectUrl = URL.createObjectURL(blob);
                  const elink = document.createElement("a");
                  elink.download = this.currentlabel+".pdf"; //下载文件名称,
                  elink.style.display = "none";
                  elink.href = objectUrl;
                  document.body.appendChild(elink);
                  elink.click();
                  URL.revokeObjectURL(elink.href); // 释放URL 对象
                  document.body.removeChild(elink);
                }
              })
              .catch(function (error) {
                console.log(error);
              });
        // file.getfile(this.id)
        //   .then((res) => {
        //     if (res) {
        //       let blob = new Blob([res.data], {
        //         type: "application/octet-stream;charset=utf-8",
        //       }); // res就是接口返回的文件流了
        //       let objectUrl = URL.createObjectURL(blob);
        //       const elink = document.createElement("a");
        //       elink.download = "xls"; //下载文件名称,
        //       elink.style.display = "none";
        //       elink.href = objectUrl;
        //       document.body.appendChild(elink);
        //       elink.click();
        //       URL.revokeObjectURL(elink.href); // 释放URL 对象
        //       document.body.removeChild(elink);
        //     }
        //   })
        //   .catch(function (error) {
        //     console.log(error);
        //   });
    },
    // deletefolderAndQuestion(id){
    //   this.isDeletefolderquestion=true
    //   question.deletefolderAndQuestion(id).then(res=>{
    //     this.$message({
    //       type: 'success',
    //       message: "删除成功"
    //     })
    //   this.getfolderQuestion(this.currentfolderId)
    //   })
    // },
    up(index,row){
        let that=this
          if(index>0){
            let update=that.folderdata[index-1]
            that.folderdata.splice(index-1,1)
            that.folderdata.splice(index,0,update)
            let temp=that.folderdata[index-1].sort
            that.folderdata[index-1].sort=that.folderdata[index].sort
            that.folderdata[index].sort=temp
          }
     },
    down(index,id){
      let that=this
      if(index<that.folderdata.length){
        let update=that.folderdata[index+1]
        that.folderdata.splice(index+1,1)
        that.folderdata.splice(index,0,update)
        let temp=that.folderdata[index+1].sort
        that.folderdata[index+1].sort=that.folderdata[index].sort
        that.folderdata[index].sort=temp
      }
    },
    updatesort(){
      this.isDeletefolderquestion==true?this.restartSort():null
 this.folderdata.forEach(i=>{
   let cu={
     id:i.id,
     sort:i.sort,
   }
   this.questionupdate.push(cu)
 })
      question.updatefolderAndQuestion(this.questionupdate).then(res=>{
        this.$message({
          type: 'success',
          message: "更新成功"
        })
      })
    this.iseditsort()
      this.folderdata=[]
      this.getfolderQuestion(this.currentfolderId)
    },

    iseditsort(){
      this.editsort=!this.editsort
      this.restartSort()
    },
    restartSort(){
      let n=1
      this.folderdata.forEach(i=>{
        i.sort=n++
      })
    },
    deletefolder(node,data){
      this.$confirm('确认删除？')
        .then(_ => {
          homework.deletefolder(data.id).then(res=>{
            this.$message({
              type: 'success',
              message: "删除成功"
            })
            this.initfolderList()
            this.currentlabel='',
              this.currentfolderId=''
          })
        })
        .catch(_ => {});

    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    openquestionadd(){
      this.addquestiondialog=true
      this.initSubject()
    },
    addquestion(){
      let questionupdatelist=[]
      this.multipleSelection.forEach(i=>{
        questionupdatelist.push(i.id)
      })
      // question.addquestionTofolder(questionupdatelist,this.currentfolderId).then(res=>{
      //   this.questionupdatelist=[]
      //   this.$message({
      //     type: 'success',
      //     message: "添加成功"
      //   })
         this.innerDrawer=false
         this.multipleSelection=[]
      // })
      this.i=1
    },
    gotoPage(page) {
      course.getCourseList(page,8,this.searchObj).then(response => {
        this.coursedata = response.data.data.items

      })
    },
    //4 点击某个一级分类，查询对应二级分类
    searchOne(subjectParentId,index) {
      //把传递index值赋值给oneIndex,为了active样式生效
      this.oneIndex = index
      this.twoIndex = -1
      this.searchObj.subjectId = ""
      this.subSubjectList = []
      //把一级分类点击id值，赋值给searchObj
      this.searchObj.subjectParentId = subjectParentId
      //点击某个一级分类进行条件查询
      this.gotoPage(1)
      //拿着点击一级分类id 和 所有一级分类id进行比较，
      //如果id相同，从一级分类里面获取对应的二级分类
      for(let i=0;i<this.subjectNestedList.length;i++) {
        //获取每个一级分类
        var oneSubject = this.subjectNestedList[i]
        //比较id是否相同
        if(subjectParentId == oneSubject.id) {
          //从一级分类里面获取对应的二级分类
          this.subSubjectList = oneSubject.children
        }
      }
    },
    //5 点击某个二级分类实现查询
    searchTwo(subjectId,index) {
      //把index赋值,为了样式生效
      this.twoIndex = index
      //把二级分类点击id值，赋值给searchObj
      this.searchObj.subjectId = subjectId
      //点击某个二级分类进行条件查询
      this.gotoPage(1)
    },
    //6 根据销量排序
    searchBuyCount() {
      //设置对应变量值，为了样式生效
      this.buyCountSort = "1"
      this.gmtCreateSort = ""
      this.priceSort = ""
      //把值赋值到searchObj
      this.searchObj.buyCountSort = this.buyCountSort
      this.searchObj.gmtCreateSort = this.gmtCreateSort;
      this.searchObj.priceSort = this.priceSort;
      //调用方法查询
      this.gotoPage(1)
    },
    openfolder(){
      this.dialogVisible=true
    },
    addfolder(){
    this.folder.teacherId=this.loginInfo.id
    homework.addfolder(this.folder).then(res=>{

      this.$message({
        type: 'success',
        message: "新建文件夹成功"
      })
      this.dialogVisible=false
      this.initfolderList()
      this.folder.label=''
    })

        },
    handleNodeClick(data) {
      this.currentlabel=data.label
      this.currentfolderId=data.id
    //  this.getfolderQuestion(data.id)
    
      this.editsort=false
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.getfolderQuestion(this.currentfolderId)
        })
        .catch(_ => {});
    },
    // getfolderQuestion(folderId){
    //   question.getQuestionsByfolderId(folderId).then(res=>{
    //     this.folderdata=res.data.data.questions
    //   })

    // },
    getcourseInfo(courseId){
      this.multipleSelection=[]
      this.innerDrawer = true
      question.getQuestionsByCourseId(courseId).then(res=>{
        this.tableData=res.data.data.questions
      })
    },
    initSubject() {
      course.getAllSubject()
        .then(response => {
          this.subjectNestedList = response.data.data.items
        //  this.searchOne(response.data.data.items[0].id,0)
        })
    },

    initfolderList(){
      homework.getfolderList(this.loginInfo.id).then(res=>{
        let current=res.data.data.folderList[0]
        this.tree=res.data.data.folderList
      // this.getfolderQuestion(current.id)
      //   this.currentlabel=current.label
      //   this.currentfolderId=current.id


       })

   //   this.getfolderQuestion()

    },


  }
}
</script>

<style scoped>
  .box{
    float: left;
    width:16%;

  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .font{
    font-size: 20px;
    work-wrap:break-word;
    color: #222226;
    font-weight: initial;
  }

</style>
